package C038;

import java.util.Stack;

/**
 * ClassName: C06
 * Package: C038
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/30 19:28
 * @Version 1.0
 * @Since 1.0
 */
public class C06 {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(11);
        stack.push(3);
        stack.push(2);
        stack.push(11);
        stack.push(12);
        stack.push(11);
        stack.push(1);

        int cnts = stack.size();
        int max = 0;
        int times = 0;

        while(cnts > 0) {
            max = stackMax(stack, cnts);
            times = stackTimes(stack, cnts, max);
            dowm(stack, cnts, max, times);
            cnts -= times;
        }
        System.out.println(stack);
    }

    // 在cnts 的层数下找栈的最大的出现的数字
    public static int stackMax(Stack<Integer> stack, int cnts) {
        if (cnts == 0 || stack.isEmpty()) {
            return Integer.MIN_VALUE;
        }

        Integer num = stack.pop();
        int i = stackMax(stack, cnts - 1);
        int res = Math.max(num, i);
        stack.push(num);
        return res;
    }

    // 在cnts层数的下，找出num出现了几次
    public static int stackTimes(Stack<Integer> stack, int cnts, int nums) {
        if (cnts == 0 || stack.isEmpty()) {
            return 0;
        }

        Integer num = stack.pop();
        int res = 0;
        if (num == nums) {
            res = 1 + stackTimes(stack, cnts - 1, nums);
        } else {
            res = stackTimes(stack, cnts - 1, nums);
        }
        stack.push(num);
        return res;
    }

    // 把最大的数进行压低
    // 出现次数这些参数都要传进来
    public static void dowm(Stack<Integer> stack, int cnts, int nums, int times) {
        if (cnts == 0 || stack.isEmpty()) {
            // 压低
            for (int i = 0; i < times; i++) {
                stack.push(nums);
            }
            return;
        }
        Integer num = stack.pop();
        dowm(stack, cnts - 1, nums, times);
        if (num != nums) {
            stack.push(num);
        }
    }

}
